<?php
/**
 * Author: yixuan
 * Desc:
 * Time: 2016/6/8 14:41
 */

namespace think\template\taglib;

use think\template\TagLib;

class Yx extends TagLib
{
    protected $tags = [
        'loop' => ['attr' => '', 'expression' => true],
    ];

    public function tagLoop($tag, $content)
    {
        $expression = ltrim(rtrim($tag['expression'], ')'), '(');
        $expression = $this->autoBuildVar($expression);
        $tmp_str = '';
        $tmp_arr = explode('$', $expression);
        $has_as = false;
        foreach ($tmp_arr as $k => $v) {
            if (empty($v)) {
                unset($tmp_arr[$k]);
            } else {
                if ($k > 1) {
                    if (!$has_as) {
                        $tmp_arr[$k] = 'as ' . '$' . $v;
                        $has_as = true;
                    } else {
                        $tmp_arr[$k] = '=>' . '$' . $v;
                    }
                    $tmp_str .= $tmp_arr[$k] . ' ';
                } else {
                    $tmp_arr[$k] = '$' . $v;
                    $tmp_str .= $tmp_arr[$k] . ' ';
                }
            }
        }
        $expression = rtrim($tmp_str);
        $parseStr = '<?php foreach(' . $expression . '): ?>';
        $parseStr .= $content;
        $parseStr .= '<?php endforeach; ?>';
        return $parseStr;
    }

}